import { message, Modal, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import TreeItem from '../TreeSide/treeItem';
import './index.less';

const Index = (props: any) => {
  const [isShow, setIsShow] = useState<boolean>(false);
  const [lbxz, setLbxz] = useState({});

  //render 列表
  const renderChildren = () => {
    return <div style={{ width: '100%', height: 260, padding: 20 }}>文章列表</div>;
  };

  const [activeKey, setActiveKey] = useState('');
  const [items, setItems] = useState([]);
  const addClass = (e,className)=>{
    for (let i = 0; i < e.length; i++) {
      const item = e[i]
      if(item.classList){
        item.classList.add(className)
      }else{
        item.className = className
      }
      if(item.childNodes){
        addClass(item.childNodes,className)
      }
    }
  }
  const initList = (id)=>{
    console.log('initList',id);
    if(!id)return
    const className = 'tabList-'+id
    const p = document.getElementsByClassName(className)[0]
    const childs = p?.childNodes || []
    addClass(childs,className)
  }
  const pId = props.id
  useEffect(()=>{
    initList(pId)
  },[pId])
  useEffect(() => {
    const newPanes = [];
    if(!props.module)return

    for (let i = 0; i < props.module.length; i++) {
      const element = props.module[i];
      newPanes.push({ label: element.name, children: renderChildren(), key: element.catId });
    }
    setItems(newPanes);
  }, [props.module]);

  useEffect(()=>{
    const bg = props.background
    if(bg && typeof bg != 'undefined'){
      const hs = document.querySelectorAll('.myTablist')
      if(hs){
        for (let i = 0; i < hs.length; i++) {
          const h = hs[i]
          if(h.style && typeof h.style != 'undefined'){
            h.style.background = `url('${bg}')`
            h.style.backgroundSize='100% 100%'
          }
        }

      }

    }
  },[props.background])
  useEffect(() => {
    let arr = [];
    if (items.length > 0) {
      for (let i = 0; i < items.length; i++) {
        const element = items[i];
        arr.push({
          catId: element.key || element.catId,
          name: element.label || element.name,
          parentId: props.id || element.parentId,
          seq: i || element.seq,
        });
      }
      props.setModule(arr);
    }
  }, [items]);

  const onChange = (newActiveKey: string) => {
    setActiveKey(newActiveKey);
  };

  const add = () => {
    const newPanes = [...items];
    newPanes.push({ label: lbxz.title, children: renderChildren(), key: lbxz.id });
    setItems(newPanes);
    setActiveKey(lbxz.id);
  };

  const remove = (targetKey: TargetKey) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = items.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      setIsShow(true);
    } else {
      remove(targetKey);
    }
  };

  //类别弹框
  const handleLbxzOk = async () => {
    const list = items.filter((item) => item.key == lbxz.id);
    if (list.length > 0) {
      message.warning('当前分类已添加，请重新选择！');
    } else {
      add();
      setIsShow(false);
    }
  };

  return (
    <>
      <Tabs
        type={ props.add?"editable-card":"card"}
        onChange={onChange}
        activeKey={activeKey}
        onEdit={onEdit}
        items={items}
        style={{height:props.height||400,border:props.border ?'2px solid gray':''}}
        className={"myTablist tabList-"+props.id}
        tabBarExtraContent={
          <div className="more">
            更多 +
          </div>
        }
      />
      <Modal
        title="类别选择"
        destroyOnClose
        open={isShow}
        onCancel={() => setIsShow(false)}
        onOk={handleLbxzOk}
      >
        <TreeItem defaultData={props.treeData} multiple={false} setSelectedTreeData={setLbxz} />
      </Modal>
    </>
  );
};
export default Index;
